<template>
  <div class="main" style="min-width: 100%">
    <div class="mainHead">
      <div class="header-left">
        <div class="pageTitle">
          <p>{{titleName}}</p>
        </div>
        <div class="pageBack" @click="back">
          <img src="../../static/image/icon/back.png">
        </div>
      </div>
      <div class="header-right">
        <div class="header-right-action">
          <img src="../../static/image/icon/teacher.png" class="header-icon"/>
          <span class="">{{teacher_name}}</span>
        </div>
        <div class="header-right-action_middle" @click="">
          <img src="../../static/image/icon/company.png" class="header-icon"/>
          <span>阳光书屋</span>
        </div>
        <div class="header-right-action">
          <img src="../../static/image/icon/logou.png" class="header-icon"/>
          <span @click="logout">退出</span>
        </div>
      </div>
    </div>

    <div class="lessoninfo-colorBar">
      <div class="classbar-item" v-for="index in [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0]"></div>
    </div>
    <div class="mainBody">
      <div class="container">
        <div class="main-title-container">

          <div class="leftTitle">
            <button class="leftIconOne" @click="changeLesson(-1)">
              <img src="../../static/image/icon/prev.png"/>
              <span>上一节</span>
            </button>
            <button class="leftIconTwo" @click="changeLesson(1)">
              <span>下一节</span>
              <img src="../../static/image/icon/next.png"/>
            </button>
            <div class="leftIconThree" @click="changeLike">
              <img src="../../static/image/icon/like1.png"/>
              <a v-if="!likeStatus">收藏</a>
              <a v-if="likeStatus">取消收藏</a>
            </div>
          </div>
          <div class="bodyCenterTop">
            <div class="action-code">
              <img src="../../static/image/barcode.jpeg">
              <span>扫码加入”阳光 创育者”参与本 课程配套培训</span>
              <!--<button class="leftIconOne" id="filter_repeat" @click="filter_repeat_images($event)">筛选</button>-->
            </div>

            <div class="action-top" v-if="true" @click="changeMaterial(0)">
              <img src="../../static/image/icon/4.png">
              <span>观看示范课</span>
            </div>
          </div>
        </div>

        <div class="bodyLeft">
          <div class="visualScreen" :class="{'fullScreen': isFullScrren}">
            <el-button @click="fullScreen"  class="fullScreenButton" > {{ isFullScrren? '退出全屏':'全屏'}} </el-button>

            <div v-for="(material, index) in materials"  :key="index" v-if="index==currentIndex" class="visualScreen-container">
              <div  class="visualScreen-container">

                <div v-if='material.type === 2 && material.isRepeatShow' class="playWindow">
                  <Video :sources="[{src: material.file.url, type: 'video/mp4'}]" :options="video.options"></Video>
                </div>

                <div v-if="material.type === 1 && material.isRepeatShow" class="videoBox">
                  <img class="audido-img"
                       :src="(coverImage || '../../static/image/coverImage/group_6.png')"/>
                  <Audio :audioList='material.file'></Audio>
                </div>

                <div v-if='material.type === 0  && material.isRepeatShow' class="imageLoop">
                  <el-carousel :autoplay="false" arrow="always" >
                    <el-carousel-item v-for="item in material.pictures"  :key="item">
                      <img class="picture" :src="item.file.url"/>
                    </el-carousel-item>
                  </el-carousel>
                </div>
                <div v-if="material.type === 3 && material.isRepeatShow" class="material-image-container">
                  <img v-bind:src="material.file.url">
                </div>

                <div v-if="material.type === 5 && material.isRepeatShow" class="material-image-container">
                  <iframe frameborder="0" :src="material.file.url" allowFullScreen="true" style="width: 100%;height: 100%"></iframe>
                  <!--<embed v-bind:src="material.externalUrl" allowFullScreen="true" quality="high" width="480" height="400" align="middle" allowScriptAccess="always" type="application/x-shockwave-flash"></embed>-->
                </div>

                <div v-if='material.type === undefined || material.type === 4' class="pdf-container">
                  <pdf
                       v-for="i in numPages"
                       :src="material.file.url"
                       :key="i"
                       :page="i"
                  ></pdf>
                </div>
              </div>
            </div>
          </div>
          <div class="material">
            <swiper :options="swiperOption" :not-next-tick="notNextTick" ref="mySwiper">
              <swiper-slide v-for="(material,index) in materials" v-if="material.isRepeatShow">
                <div class="material-item" @click="changeMaterial(index)">
                  <img v-bind:src="material.file.url" v-if="material.type === 3"/>
                  <img src="/static/img/smile.3331614.png" v-if="material.type === 5"/>
                  <img src="/static/img/smile.3331614.png" v-if="material.type === 1"/>
                  <div class='material-item-video-container' v-if="material.type === 2">
                    <video v-bind:src="material.file.url"></video>
                  </div>
                  <img v-if="material.type === 0" src="/static/img/group_6.2e2bc47.png" />
                  <pdf class="pdf-style" v-bind:src="material.file.url" v-if="material.type === undefined || material.type == 4"></pdf>
                  <div class="material-item-name">{{material.name}}</div>
                </div>
              </swiper-slide>
              <div class="swiper-pagination" style="display: none" slot="pagination"></div>
            </swiper>

            <div class="swiper-prev" @click="prev($event)"><img src="/static/image/icon/next2.png"></div>
            <div class="swiper-next" @click="next($event)"><img src="/static/image/icon/next2.png"></div>
          </div>
        </div>

        <div class="bodyCenter">

          <div class="markdown">
            <div class="js-markdown-container"></div>
            <VueMarkdown style='display: none' :source="lessonPlan" @rendered="handelMarkdwonShow"></VueMarkdown>
          </div>

        </div>
      </div>

    </div>

  </div>
</template>
<script>
  import Analytics from "@/js/analytics.js"
  import Data from "@/js/server.js"
  import pdf from 'vue-pdf'
  export default {
    data() {
      return {
        isFullScrren: false,
        isshowpdf: true,
        numPages: 1,
        video: {
          sources: [],
          options: {
            autoplay: true,
            volume: 0.6,
            poster: ''
          }
        },
        lessonPlanHtml: "",
        currentIndex: 0,
        materials: [],
        lessonPlan: '',
        titleName: '',
        likeStatus: false,
        notNextTick: true,
        teacher_name: '',
        isFilter:false,
        swiperOption: {
          slidesPerGroup: 5,
          slidesPerView: 5,
          pagination: {
            el: '.swiper-pagination',
            clickable: true
          },
          onTransitionStart(swiper) {
            console.log(swiper)
          },
        },
      }
    },
    components:{
      pdf
    },
    computed: {
      swiper: function () {
        return this.$refs.mySwiper.swiper
      },
    },
    mounted: function () {
      this.getParams();
      this.inspectLike();
      this.getUsername();
    },
    methods: {
      fullScreen(){
        this.isFullScrren = ! this.isFullScrren
      },
      getUsername() {
        var self = this;
        var userId = AV.User.current().toJSON().objectId
        var query = new AV.Query('_User');
        query.get('' + userId).then(function (todo) {
          self.teacher_name = todo.toJSON().username
        }, function (error) {
          // 异常处理
        });
      },
      getParams: function () {
        var self = this
        var id = self.$route.params.id
        var sign = id.substring(id.length - 3, id.length)
        if (sign == 'his') {
          var lessonId = id.substring(0, id.length - 3)
          var startDateQuery = new AV.Query('LessonSnapshot');
          startDateQuery.equalTo('lessonId', lessonId)
          var endDateQuery = new AV.Query('LessonSnapshot');
          startDateQuery.equalTo('isChecked', 3);
          var query = AV.Query.and(startDateQuery, endDateQuery);
          query.find().then(function (result) {
            if (result.length == 1) {
              self.manifestUrl = result[0].toJSON().manifest_json.url //只有一个版本的json路径
            } else if (result.length > 1) {
              var version = 1;
              var lesson = '';
              result.forEach(function (item) {

                if (item.attributes.version_code > version) {
                  version = item.attributes.version_code
                  lesson = item.toJSON().manifest_json.url
                }
              })
              self.manifestUrl = lesson //有版本号最大的json路径
            }
            self.getHistoryJson(self.manifestUrl) //获取json内容
          })
        } else {
          var query = new AV.Query('Lesson')
          console.log(id)
          query.get(id).then(function (todo) {
            console.log(todo)
            self.titleName = todo.attributes.name
            self.name = todo.attributes.name;
            self.planId = todo.attributes.plan.id;
            self.coverImage = todo.toJSON().coverImage ? todo.toJSON().coverImage.url : '';
            console.log(self.coverImage)
            self.getPlan();
            self.getMaterialId().then(materailIds => {
              return self.getMaterials(materailIds)
            }).then((materials) => {
              self.materials = materials
              console.log(self.materials)
              self.changeCurrentIndex(materials);

              self.getPlan();
            })

          }, function (error) {

          })
        }
      },
      changeCurrentIndex:function(all_material){
        var index = all_material.findIndex(function (material_item) {
          return material_item.isRepeatShow == true;
        });
        this.currentIndex = index;
        this.getMaterialPdfNumberPages(index)
      },
      getHistoryJson: function (jsonUrl) {
        var self = this;
        self.$http.get(jsonUrl).then(function (response) {
          self.titleName = response.data.name;
          let lessonPlan = response.data.content;
          self.name = response.data.name;
          self.coverImage = response.data.coverImage ? response.data.coverImage.url : '';
          self.materialHistory = response.data.materials;
          let materialList = {};
          self.materialHistory.forEach(function (material) {
            if (material.parent) {
              material.file = {url: material.url}
              let atlas = materialList[material.parent] || {pictures: []}
              atlas.pictures.push(material)
              materialList[material.parent] = atlas;
              return
            }
            if (materialList[material.id]) {
              materialList[material.id].objectId = material.id;
              materialList[material.id].name = material.name;
              materialList[material.id].type = material.type;
              materialList[material.id].file = {url: material.url};
              materialList[material.id].file_index = material.file_index;
              return
            }
            material.objectId = material.id;
            material.file = {url: material.url}
            materialList[material.id] = material;
          })

          materialList = Object.keys(materialList).map(key => {
            return materialList[key]
          }).sort(function (a, b) {
            return a.file_index > b.file_index
          });
          console.log(self.materials);


          if (materialList) {
            var markdown = lessonPlan;
            materialList.forEach(function (material) {
              // material.hadInplan = false
              if (material.type === 3) {
                console.log()
                markdown = markdown.replace(material.id, material.file.url)
              }
              if (material.type === 0) {

                material.pictures.forEach(picture => {
                  markdown = markdown.replace(picture.id, picture.file.url)
                })
              }
            })
            self.lessonPlan = markdown
          } else {
            self.lessonPlan = lessonPlan.content
          }
            self.getMaterialsToBurPoint();
          self.materials = materialList;
          self.changeCurrentIndex(materialList);
        })
      },
      back: function () {
        this.$router.push({
          path: '/lessonList'//lesson
        })
      },
      getMaterialId: function () {
        var self = this;
        return new Promise(resolve => {

          var id = self.$route.params.id;
          var query = new AV.Query('LessonMaterial')
          var lessonId = AV.Object.createWithoutData('Lesson', id);
          query.equalTo('lesson', lessonId);
          query.find().then(function (materialList) {
            let materailIds = materialList.map(function (item) {
              return item.attributes.material.id
            });
            resolve(materailIds)
          })
        })
      },
      getMaterials(materailIds) {
        if (this.materialHistory) {
          return new Promise(resolve => {
            resolve(this.materialHistory)
          })
        }
        return new Promise(resolve => {
          var query = new AV.Query('Material')
          query.containedIn('objectId', materailIds);
          query.find().then(function (materialList) {
            var allPromise = [];
            materialList.forEach(material => {
              material = material.toJSON();
              if (material.type === 0) {
                allPromise.push(new Promise(resolve => {
                  new AV.Query('Material')
                    .equalTo('parent', AV.Object.createWithoutData('Material', material.objectId))
                    .find().then(function (pictures) {
                    resolve({objectId: material.objectId, pictures: pictures.map(picture => picture.toJSON())})
                  })
                }))
              }
            });

            Promise.all(allPromise).then((pictures) => {
              materialList = materialList.map(material => material.toJSON());
              materialList.forEach(material => {
                pictures.forEach(picture => {
                  if (material.objectId === picture.objectId) {
                    material.pictures = picture.pictures;
                  }
                })
              });


              resolve(materialList)
            })


          })
        })

      },


      getPlan: function () {
        var self = this;
        var planId = self.planId;
        var query = new AV.Query('LessonPlan')
        query.get(planId).then(function (lessonPlan) {
          lessonPlan = lessonPlan.toJSON();
          if (self.materials) {
            var markdown = lessonPlan.content;
            self.materials.forEach(function (material) {
              if (material.type === 3) {
                markdown = markdown.replace(material.objectId, material.file.url)
              }
              if (material.type === 0) {
                material.pictures.forEach(picture => {
                  markdown = markdown.replace(picture.objectId, picture.file.url)
                })
              }

            })

            self.lessonPlan = markdown
          } else {
            self.lessonPlan = lessonPlan.content
          }
            self.getMaterialsToBurPoint();
        })
      },
      getMaterialsToBurPoint: function () {
        var self = this;
        this.materials.forEach(function (material, index) {
          if (index === self.currentIndex) {
            if (material.type === 2) {
              self.burPoint(material.file.name, '视频');
            } else if (material.type === 1) {
              self.burPoint(material.file.name, '音频')
            } else if (material.type === 0) {
              self.burPoint(material.name, '绘本')
            }
            else if (material.type === 3) {
              self.burPoint(material.name, '图片')
            }
            else if (material.type === undefined || material.type == 4){
              self.burPoint(material.name, 'pdf')
            }
          }
        })
      },
      burPoint: function (resName, resType) {
        var actionList = ['sourceOpen']
        var userId = AV.User.current().toJSON().objectId
        Analytics.openRes(resName, userId, resType)
      },
      playVideo: function (id, resName) {
        this.burPoint(resName, '视频')
        this.showVideo = true;
        this.showAudio = false;
        var self = this;
        self.video.sources = [];
        var query = new AV.Query('Material');
        query.get(id).then(function (todo) {
          var videoUrl = todo.attributes.file.attributes.url
          self.name = todo.attributes.file.attributes.name
          var video = [{src: videoUrl, type: 'video/mp4'}]
          self.video.sources.push(video)
        }, function (error) {
          // 异常处理
        });
      },
      playAudio: function (resName) {
        this.burPoint(resName, '音频')
        this.showVideo = false;
        this.showAudio = true
      },
      playImage: function (atlasId) {
        var self = this
        self.burPoint(self.name, '绘本')
        self.imageId = atlasId;
        this.getPicture(atlasId)
      },
      playPicture: function () {
        console.log(this.informationList)
        this.showVideo = false;
        this.showAudio = false;
      },
      getPicture: function (atlasId) {
        var self = this
        var picture = [];
        var query = new AV.Query('Material');
        var todoFolder = AV.Object.createWithoutData('Material', atlasId);
        query.equalTo('parent', todoFolder);
        query.find().then(function (result) {
          result.forEach(function (item) {
            picture.push(item.attributes.file.attributes.url)
          });
          self.pictures = picture;
          self.showImage = true;
        })
      },
      checkPic: function (index, picID) {
        var self = this;
        self.popupImgFlag = true;
        self.photoArg = self.items[index].picUrl;
        this.swiper.slideTo(picID, 1000, false);    //slideTo()
        document.body.style.overflowY = "hidden";
        document.getElementById("app").style.overflowY = "hidden";
      },

      prev(e) {
        let prevElement = window.document.getElementsByClassName('swiper-pagination-bullet-active')[0].previousSibling;
        if (!prevElement) return;
        prevElement.click()
      },
      next() {
        let nextElement = window.document.getElementsByClassName('swiper-pagination-bullet-active')[0].nextSibling
        if (!nextElement) return;
        nextElement.click()
      },
      getMaterialPdfNumberPages(index){
        console.log("getMaterialPdfNumberPages")
        if (this.materials[index].type == undefined || this.materials[index].type == 4) {
          var loadingTask = pdf.createLoadingTask(this.materials[index].file.url);
          loadingTask.then(pdf1 => {
            this.numPages = pdf1.numPages;
          })
        }
      },
      changeMaterial(index) {
        console.log("=======changeMaterial=="+index)
        this.currentIndex = index
        this.getMaterialsToBurPoint()
        this.getMaterialPdfNumberPages(index)
      },
      handelMarkdwonShow(lessonPlanHtml) {
        if (!lessonPlanHtml) return
        var lessonPlanInfo = lessonPlanHtml.split('<h2>')


        var fristContent = lessonPlanInfo.shift();
        lessonPlanInfo = lessonPlanInfo.join('</div><div class="card"><h2>')


        lessonPlanInfo = fristContent + "<div class='card'><h2>" + lessonPlanInfo
        lessonPlanInfo = lessonPlanInfo + '</div>';

        document.getElementsByClassName('js-markdown-container')[0].innerHTML = lessonPlanInfo
      },
      changeLesson(changeCount) {
        let currentIndex = Number(localStorage.getItem('currentLessonIndex') || "1")
        let lessonList = JSON.parse(localStorage.getItem('lessonsList') || "[]")
        console.log(currentIndex)


        if (!lessonList.length) {
          return this.$message({
            type: 'success',
            message: '已到尽头'
          })
        }

        let nextIndex = currentIndex + changeCount;

        if (nextIndex < 0 || lessonList.length <= nextIndex) {
          return this.$message({
            type: 'success',
            message: '已到尽头'
          })
        }

        let nextLesson = lessonList[nextIndex];
        let id = nextLesson.id + (nextLesson.verstion || '');

        localStorage.setItem('currentLessonIndex', nextIndex);
        this.burPoint(nextLesson.subject, id);
        this.$router.push({
          path: '/lessonInfo/' + id + "?isRefresh=false" //lesson
        })
        window.location.reload()
      },
      changeLike: function () {
        var self = this
        if (self.likeStatus == false) {
          self.likeStatus = true
          self.likeImgUrl = '../../static/image/on.svg'
          var timestamp = Date.parse(new Date());
          var lessonId = ''
          var id = self.$route.params.id
          var sgin = id.substring(id.length - 3, id.length)
          if (sgin == 'his') {
            lessonId = id.substring(0, id.length - 3)
          } else {
            lessonId = self.$route.params.id
          }
          var data = {
            "collectionActionArr": [{
              "lessonId": lessonId,
              "lastModificationTime": timestamp,
              "action": self.likeStatus
            }]
          }
          AV.Cloud.run('collection', data).then(
            function (value) {
              self.$message({
                type: 'success',
                message: '收藏课程成功'
              })
              res.send(value)
            }, function (error) {
              self.$message({
                type: 'error',
                message: '收藏课程失败'
              })
              res.send(error)
            }
          )
        } else {
          self.likeStatus = false
          self.likeImgUrl = '../../static/image/default.svg'
          var timestamp = Date.parse(new Date());
          var id = self.$route.params.id
          var lessonId
          var id = self.$route.params.id
          var sgin = id.substring(id.length - 3, id.length)
          if (sgin == 'his') {
            lessonId = id.substring(0, id.length - 3)
          } else {
            lessonId = self.$route.params.id
          }
          var data = {
            "collectionActionArr": [{
              "lessonId": lessonId,
              "lastModificationTime": timestamp,
              "action": self.likeStatus
            }]
          }
          AV.Cloud.run('collection', data).then(
            function (value) {
              self.$message({
                type: 'success',
                message: '取消收藏'
              })
              res.send(value)
            }, function (error) {
              self.$message({
                type: 'error',
                message: '取消收藏失败'
              })
              res.send(error)
            }
          )
        }
      },
      inspectLike: function () {
        let self = this;
        let lessonId = '';
        let id = self.$route.params.id;
        let sgin = id.substring(id.length - 3, id.length)
        if (sgin === 'his') {
          lessonId = id.substring(0, id.length - 3)
        } else {
          lessonId = self.$route.params.id
        }
        Data.checkoutLike(function (result) {
          // console.log(result)
          if (result.indexOf(lessonId) !== -1) {
            self.likeStatus = true
          }
        })
      },
      logout: function () {
        var currentUser = AV.User.current();
        var endtime = new Date().getTime()
        Analytics.useApp(currentUser.toJSON().objectId, window.localStorage.getItem('openTime'), endtime)
        localStorage.removeItem("useTime");
        AV.User.logOut()
        this.$router.push({path: '/'})
        document.body.parentNode.style.overflow = "scroll"
      },

    }
  }
</script>

<style src="../css/lessonInfo.css">
</style>
<style src="../css/common.css">
</style>

